﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.IO;

namespace ADECMS.UserPages
{
    public partial class FileDownload : System.Web.UI.Page
    {
        ADECMSDBDataContext cmsdb;
        static String fileName;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            cmsdb = new ADECMSDBDataContext();
            if (!Page.IsPostBack)
            {
                LabelOpis.Visible = false;
                fileName = "";
                CATEGORY kat = cmsdb.CATEGORies.First();
                labelCategory_id.Text = kat.id.ToString();
                HttpCookie loginCookie = Request.Cookies["AuthCookie"];
                if (Request.IsAuthenticated)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(loginCookie.Value);
                    Label5.Text = "Logovani ste " + ticket.Name.ToString();

                    var useri = from k in cmsdb.USERs
                                from p in cmsdb.USER_TYPEs
                                where k.username == ticket.Name && k.user_type_id == p.id && p.type == "Administrator"
                                select k;
                    try
                    {
                        USER kor = useri.First();
                        MenuItem apanel = new MenuItem("Admin panel");
                        Menu1.Items.Add(apanel);
                    }
                    catch (System.InvalidOperationException)
                    {
                        return;
                    }
                }
            }
            GridView1.DataBind();
        }

        protected void ButtonBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("/UserPages/Start.aspx");
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
             try
             {
                 LabelNaziv.Visible = true;
                 LabelNaziv.Text = "Naziv fajla je: " + GridView1.SelectedRow.Cells[1].Text;

                 FILE fil = cmsdb.FILEs.Single(f => f.name == GridView1.SelectedRow.Cells[1].Text);

                 if (fil.description != "")
                 {
                     LabelOpis.Visible = true;
                     LabelOpisText.Visible = true;
                     LabelOpisText.Text = fil.description;
                 }
                 else
                 {
                     LabelOpis.Visible = false;
                     LabelOpisText.Visible = false;
                 }
                 BtnDownload.Visible = true;

                 fileName = GridView1.SelectedRow.Cells[1].Text;
                     Image1.Visible = true;
                     Image1.ImageUrl = "FileDownloadImageHandle.ashx?fileName=" + fileName;

             }
             catch (Exception ex)
             {
                 Response.Write(ex.Message);
             }
        }

        protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
        {
            switch (e.Item.Text)
            {
                case "Sign out":
                    FormsAuthentication.SignOut();
                    Response.Redirect("/Default.aspx");
                    break;
                case "Dodaj novost":
                    Response.Redirect("/UserPages/AddNews.aspx");
                    break;
                case "Pretraga":
                    Response.Redirect("/UserPages/Search.aspx");
                    break;
                case "Admin panel":
                    Response.Redirect("/UserPages/AdminPanel.aspx");
                    break;
                case "File upload":
                    Response.Redirect("/UserPages/FileUpload.aspx");
                    break;
                case "File download":
                    Response.Redirect("/UserPages/FileDownload.aspx");
                    break;
                case "Upload prezentacije":
                    Response.Redirect("/UserPages/PresentationUpload.aspx");
                    break;
                case "Pregled prezentacije":
                    Response.Redirect("/UserPages/PresentationView.aspx");
                    break;
                case "Pregledaj profil":
                    Response.Redirect("/UserPages/ProfileView.aspx");
                    break;
                case "Edituj profil":
                    Response.Redirect("/UserPages/ProfileEdit.aspx");
                    break;
            }
        }

        protected void DropKategorija_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DobaviCategoryID();
                GridView1.DataBind();
            }catch(Exception ex){
                Response.Write(ex.Message);
            }
        }

        private void DobaviCategoryID()
        {
            String kategorija = DropKategorija.SelectedItem.ToString();
            CATEGORY kat = cmsdb.CATEGORies.Single(k => k.name == kategorija&&k.type=="file");
            labelCategory_id.Text = kat.id.ToString();
        }

        private void DownloadFile(string fname, bool forceDownload)
        {
            string path = MapPath("/Uploads/Files/"+fname);
            string name = Path.GetFileName(path);
            string ext = Path.GetExtension(path);
            string type = "";

            if (ext != null)
            {
                switch (ext.ToLower())
                {
                    case ".htm":
                    case ".html":
                        type = "text/HTML";
                        break;

                    case ".txt":
                        type = "text/plain";
                        break;

                    case ".doc":
                    case ".docx":
                    case ".rtf":
                        type = "Application/msword";
                        break;
                }
            }
            if (forceDownload)
            {
                Response.AppendHeader("content-disposition",
                    "attachment; filename=" + name);
            }
            if (type != "")
                Response.ContentType = type;
            Response.WriteFile(path);
            Response.End();
        }

        protected void BtnDownload_Click(object sender, EventArgs e)
        {
            DownloadFile(fileName, true);

            
        }
    }
}
